<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib prefix="mytag" uri="/WEB-INF/tag/tag.tld" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://www.layuicdn.com/layui-v2.5.6/css/layui.css">
    <link rel="stylesheet" href="/ncpsy/static/css/style.css">
    <title>溯源环节模板管理</title>
    <style>
        .raw-text-container {
            /*margin: 10px 0;*/
            text-align: left;
            color: #333;
        }

        .layui-row {
            margin-top: 30px;
        }

        .test-test {
            padding: 10px 0;
        }

        .test-test > pre {
            outline: 1px solid #ccc;
            background: #f8f8f8;
            padding: 20px;
        }

        h2 {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
<div class="layui-container">
    <div class="page-header">
        <h1 class="title">溯源环节模板管理</h1>
    </div>
    <div class="table-container">
        <div class="table-content">
            <div class="table-card-body">
                <div class="table-tools">
                    <button type="button" class="layui-btn add-template-btn">新建模板</button>
                </div>
                <table id="list" lay-skin="line" lay-filter="templateList" lay-data="{id: 'idTemplateTable'}"></table>
            </div>
        </div>
    </div>

    <!--新建溯源环节模板-->
    <div class="drawer-right new-template-container">
        <div class="drawer-mask"></div>
        <div class="drawer-content-wrapper">
            <!--header-->
            <div class="ant-drawer-header">
                <div class="ant-drawer-title">新建模板</div>
                <button aria-label="Close" class="ant-drawer-close"><i aria-label="图标: close"
                                                                       class="anticon anticon-close">
                    <svg viewBox="64 64 896 896" focusable="false" class="" data-icon="close" width="1em" height="1em"
                         fill="currentColor" aria-hidden="true">
                        <path d="M563.8 512l262.5-312.9c4.4-5.2.7-13.1-6.1-13.1h-79.8c-4.7 0-9.2 2.1-12.3 5.7L511.6 449.8 295.1 191.7c-3-3.6-7.5-5.7-12.3-5.7H203c-6.8 0-10.5 7.9-6.1 13.1L459.4 512 196.9 824.9A7.95 7.95 0 0 0 203 838h79.8c4.7 0 9.2-2.1 12.3-5.7l216.5-258.1 216.5 258.1c3 3.6 7.5 5.7 12.3 5.7h79.8c6.8 0 10.5-7.9 6.1-13.1L563.8 512z"></path>
                    </svg>
                </i></button>
            </div>
            <!--body-->
            <div class="ant-drawer-body">
                <form name="form" class="layui-form ant-form ant-form-horizontal">
                    <div>
                        <div class="traceScrollWrap newTraceScrollWrap">

                            <div class="layui-form-item">
                                <label class="layui-form-label">模板名称：</label>
                                <div class="layui-input-block">
                                    <input type="text" name="tpName" required lay-verify="required" placeholder="请输入"
                                           autocomplete="off"
                                           class="layui-input templateName">
                                </div>
                            </div>
                            <!--在下面添加新增环节-->
                        </div>

                        <button type="button"
                                class="layui-btn layui-btn-primary addBtn add-huanjie-template ant-btn-dashed">
                            <i aria-label="图标: plus" class="anticon anticon-plus">
                                <svg viewBox="64 64 896 896" focusable="false" class="" data-icon="plus" width="1em"
                                     height="1em"
                                     fill="currentColor" aria-hidden="true">
                                    <path d="M482 152h60q8 0 8 8v704q0 8-8 8h-60q-8 0-8-8V160q0-8 8-8z"></path>
                                    <path d="M176 474h672q8 0 8 8v60q0 8-8 8H176q-8 0-8-8v-60q0-8 8-8z"></path>
                                </svg>
                            </i>
                            <span>添加新的溯源环节（最多 10 个）</span>
                        </button>
                    </div>
                </form>
            </div>
            <!--footer-->
            <div class="footer">
                <button type="button" class="layui-btn cancel-add-template layui-btn-primary"
                        style="margin-right: 8px;"><span>取 消</span>
                </button>
                <button type="button" class="layui-btn confirm-add-template"><span>确 定</span></button>
            </div>
        </div>
    </div>
    <!--查看溯源环节模板-->
    <div class="drawer-right view-template-container">
        <div class="drawer-mask"></div>
        <div class="drawer-content-wrapper">
            <!--header-->
            <div class="ant-drawer-header">
                <div class="ant-drawer-title">查看溯源环节详情</div>
                <button aria-label="Close" class="ant-drawer-close"><i aria-label="图标: close"
                                                                       class="anticon anticon-close">
                    <svg viewBox="64 64 896 896" focusable="false" class="" data-icon="close" width="1em" height="1em"
                         fill="currentColor" aria-hidden="true">
                        <path d="M563.8 512l262.5-312.9c4.4-5.2.7-13.1-6.1-13.1h-79.8c-4.7 0-9.2 2.1-12.3 5.7L511.6 449.8 295.1 191.7c-3-3.6-7.5-5.7-12.3-5.7H203c-6.8 0-10.5 7.9-6.1 13.1L459.4 512 196.9 824.9A7.95 7.95 0 0 0 203 838h79.8c4.7 0 9.2-2.1 12.3-5.7l216.5-258.1 216.5 258.1c3 3.6 7.5 5.7 12.3 5.7h79.8c6.8 0 10.5-7.9 6.1-13.1L563.8 512z"></path>
                    </svg>
                </i></button>
            </div>
            <!--body-->
            <div class="ant-drawer-body">
                <div class="ant-descriptions" style="margin-bottom: 24px;">
                    <div class="ant-descriptions-title">基本信息</div>
                    <div class="ant-descriptions-view">
                        模板名称：<span class="viewTemplateName"></span>

                    </div>
                </div>
                <ul class="layui-timeline viewLayUITimeLine">
                    <!--在这里渲染环节的timeline-->
                </ul>
            </div>

        </div>
    </div>
    <!--编辑溯源环节模板-->
    <div class="drawer-right edit-template-container">
        <div class="drawer-mask"></div>
        <div class="drawer-content-wrapper">
            <!--header-->
            <div class="ant-drawer-header">
                <div class="ant-drawer-title">编辑模板</div>
                <button aria-label="Close" class="ant-drawer-close"><i aria-label="图标: close"
                                                                       class="anticon anticon-close">
                    <svg viewBox="64 64 896 896" focusable="false" class="" data-icon="close" width="1em" height="1em"
                         fill="currentColor" aria-hidden="true">
                        <path d="M563.8 512l262.5-312.9c4.4-5.2.7-13.1-6.1-13.1h-79.8c-4.7 0-9.2 2.1-12.3 5.7L511.6 449.8 295.1 191.7c-3-3.6-7.5-5.7-12.3-5.7H203c-6.8 0-10.5 7.9-6.1 13.1L459.4 512 196.9 824.9A7.95 7.95 0 0 0 203 838h79.8c4.7 0 9.2-2.1 12.3-5.7l216.5-258.1 216.5 258.1c3 3.6 7.5 5.7 12.3 5.7h79.8c6.8 0 10.5-7.9 6.1-13.1L563.8 512z"></path>
                    </svg>
                </i></button>
            </div>
            <!--body-->
            <div class="ant-drawer-body">
                <form class="layui-form ant-form ant-form-horizontal">
                    <div>
                        <div class="traceScrollWrap editTraceScrollWrap">
                            <!--在下面渲染模板名称和环节列表-->
                        </div>

                        <button type="button"
                                class="layui-btn layui-btn-primary addBtn add-huanjie-template ant-btn-dashed">
                            <i aria-label="图标: plus" class="anticon anticon-plus">
                                <svg viewBox="64 64 896 896" focusable="false" class="" data-icon="plus" width="1em"
                                     height="1em"
                                     fill="currentColor" aria-hidden="true">
                                    <path d="M482 152h60q8 0 8 8v704q0 8-8 8h-60q-8 0-8-8V160q0-8 8-8z"></path>
                                    <path d="M176 474h672q8 0 8 8v60q0 8-8 8H176q-8 0-8-8v-60q0-8 8-8z"></path>
                                </svg>
                            </i>
                            <span>添加新的溯源环节（最多 10 个）</span>
                        </button>
                    </div>
                </form>
            </div>
            <!--footer-->
            <div class="footer">
                <button type="button" class="layui-btn cancel-add-template layui-btn-primary"
                        style="margin-right: 8px;"><span>取 消</span>
                </button>
                <button type="button" class="layui-btn"><span>确 定</span></button>
            </div>
        </div>
    </div>
</div>


<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.12.4/jquery.js"></script>
<%--<script src="/ncpsy/static/js/public.js"></script>--%>
<script src="https://www.layuicdn.com/layui-v2.5.6/layui.js"></script>

<script>

    // 将UTC时间转换成北京时间
    function utc2beijing(utc_datetime) {
        // 处理成为时间戳
        timestamp = new Date(Date.parse(utc_datetime));
        timestamp = timestamp.getTime();
        timestamp = timestamp / 1000;

        // 增加8个小时，北京时间比utc时间多八个时区
        var timestamp = timestamp + 8 * 60 * 60;

        // 时间戳转为时间
        var beijing_datetime = new Date(parseInt(timestamp) * 1000).toLocaleString();
        return beijing_datetime; // 2017-03-31 16:02:06
    }


    function getParamsFromUrl() {
        const paramsObj = {};
        let params = location.search.split('?');
        for (let i = 0, len = params.length; i < len; i++) {
            if (!params[i]) {
                continue
            }
            const temp = params[i].split('=');
            paramsObj[temp[0]] = temp[1]
        }
        return paramsObj
    }


    const BASE_URL = '/ncpsy';
    $(document).ready(function () {
        // 动态添加下拉框
        var selectOptions = [];
// 获取运输商列表,并渲染
        getTransportList().then(res => {
            selectOptions = res;
            renderAll();
        }).catch(err => console.log(err));

        function renderAll() {
            selectEl = `<div class="layui-form-item">
    <label class="layui-form-label">选择运输商</label>
    <div class="layui-input-block">
      <select class="drawer-select" name="qid" lay-verify="required">
        <option value="">请选择</option>
        ` + renderSelectOptions(selectOptions) + `
      </select>
    </div>
  </div>`;
            // 添加环节
            huanjieHtml = `<div class="addItemWrap">
                <div class="header">
                  <i aria-label="图标: unordered-list" class="anticon anticon-unordered-list"
                     style="font-size: 16px;">
                    <svg viewBox="64 64 896 896" focusable="false" class="" data-icon="unordered-list" width="1em"
                         height="1em" fill="currentColor" aria-hidden="true">
                      <path d="M912 192H328c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h584c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm0 284H328c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h584c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zm0 284H328c-4.4 0-8 3.6-8 8v56c0 4.4 3.6 8 8 8h584c4.4 0 8-3.6 8-8v-56c0-4.4-3.6-8-8-8zM104 228a56 56 0 1 0 112 0 56 56 0 1 0-112 0zm0 284a56 56 0 1 0 112 0 56 56 0 1 0-112 0zm0 284a56 56 0 1 0 112 0 56 56 0 1 0-112 0z"></path>
                    </svg>
                  </i>
                </div>
                <div class="content">
                  <div class="layui-form-item">
                    <label class="layui-form-label">环节名称：</label>
                    <div class="layui-input-block">
                      <input type="text" name="lname" required lay-verify="required" placeholder="请输入"
                             autocomplete="off" class="layui-input">
                    </div>
                  </div>
                  ` + selectEl + `
                  <div class="layui-form-item">
                    <label class="layui-form-label">环节说明：</label>
                    <div class="layui-input-block">
                      <input type="text" name="nexplain" required lay-verify="required" placeholder="请输入"
                             autocomplete="off" class="layui-input">
                    </div>
                  </div>
                </div>
                <div class="delete delete-huanjie-template"><a>删除</a></div>
              </div>`;
        }

        let huanjieHtml, selectEl;
        // 添加环节按钮事件
        $('.add-huanjie-template').on('click', function (e) {
            const newTraceScrollWrap = $('.newTraceScrollWrap');
            if (newTraceScrollWrap.children().length >= 10) {
                return false
            }
            const $newTemp = document.createElement('div');
            $newTemp.setAttribute('class', 'new-add-huanjie-template-wrapper');
            $newTemp.innerHTML = huanjieHtml;
            newTraceScrollWrap.append($newTemp)
        });

        /*
        * 新建、查看、编辑模板页面操作
        * */
        $('body').on('click', '.delete-huanjie-template', function (e) { // 删除单个环节
            $(this).parents('.new-add-huanjie-template-wrapper').remove();
        })
            .on('click', '.ant-drawer-close', function () { // 关闭新建、编辑、查看模板
                $(this).parents('.drawer-right').fadeOut()
            })
            .on('click', '.cancel-add-template', function () { // 取消新建、编辑模板
                $(this).parents('.drawer-right').fadeOut()
            })
            .on('click', '.drawer-mask', function () { // 点击mask遮罩关闭右侧页面
                $(this).parents('.drawer-right').fadeOut()
            })
            .on('change', '.drawer-select', function () {
                console.log($(this).val())
            })
            .on('click', '.confirm-add-template', function () { // 确认添加环节模板
                const arr = $('form').serializeArray();
                let tpName = arr[0].value;
                if (!tpName) {
                    layer.msg('请输入模板名称');
                    return false
                }
                let nodeList = [];
                if (arr.length > 1) {
                    for (let i = 1, len = arr.length; i < len; i += 3) {
                        const obj = {};
                        obj[arr[i].name] = arr[i].value;
                        obj[arr[i + 1].name] = arr[i + 1].value;
                        obj[arr[i + 2].name] = arr[i + 2].value;
                        nodeList.push(obj)
                    }
                }
                var qyid = localStorage.getItem('qyid');
                const data = {
                    tpName,
                    nodeList: nodeList,
                    qyid
                };
                submitNewTemplate(data)
            });

        // 提交到后台
        function submitNewTemplate(data) {
            $.ajax({
                type: 'post',
                url: BASE_URL + '/addTp',
                contentType: 'application/json;charset=utf-8',
                data: JSON.stringify(data),
                success(res) {
                    if (res.code === 200) {
                        layer.msg(res.message, {icon: 6});
                        hideTemplate('.new-template-container'); // 关闭右侧页面
                        updateTamplateTable(); // 更新模板列表
                    }
                },
                error(err) {
                    console.log(err)
                }
            })
        }

        // 新建模板
        $('.add-template-btn').on('click', function () {
            showTemplate('.new-template-container');
            console.log(selectOptions)
        });
    });

    // 显示模板
    function showTemplate(el) {
        $(el).fadeIn()
    }

    // 关闭模板
    function hideTemplate(el) {
        $(el).fadeOut()
    }

    // 运输商列表HTML
    function renderSelectOptions(data) {
        if (!data || !data.length) {
            return false
        }
        let select = '';
        for (let i = 0, len = data.length; i < len; i++) {
            const $option = `<option value="` + data[i].qyid + `">` + data[i].qymc + `</option>`;
            select += $option
        }
        return select
    }


    // 查看————获取模板环节信息并渲染到页面
    function renderHuanjieDataView(data) {
        // 先清空元素内容，再渲染
        const viewLayUITimeLine = $('.viewLayUITimeLine');
        viewLayUITimeLine.empty();
        $('.viewTemplateName').text(data.tpName);
        const list = data.nodeList;
        if (!list || !list.length) {
            return false
        }
        for (let i = 0, len = list.length; i < len; i++) {
            const $el = `<li class="layui-timeline-item">
            <i class="layui-icon layui-timeline-axis">&#xe63f;</i>
            <div class="layui-timeline-content layui-text">
              <h3 class="layui-timeline-title">` + list[i].lname + `</h3>
              <p>
                环节描述：` + list[i].nexplain + `
              </p>
            </div>
          </li>`;
            viewLayUITimeLine.append($el)
        }
    }

    // 获取运输商列表
    function getTransportList() {
        return new Promise((resolve, reject) => {
            $.ajax({
                url: BASE_URL + '/queryUserOne/2',
                type: 'get',
                contentType: 'application/json;charset=utf-8;',
                success: function (res) {
                    if (res.code === 200) {
                        resolve(res.data);
                    }
                },
                error(err) {
                    reject(err)
                }
            })
        })
    }
</script>

<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="detail">详情</button>
        <!--<button class="layui-btn layui-btn-sm" lay-event="update">编辑</button>-->
        <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="delete">删除</button>
    </div>
</script>

<script>
    // 获取模板列表并渲染
    function getTemplateList() {
        return new Promise((resolve, reject) => {
            var qyid = localStorage.getItem('qyid');
            $.ajax({
                url: BASE_URL + '/queryTpAll/' + qyid,
                type: 'get',
                contentType: 'application/json;charset=utf-8;',
                success: function (res) {
                    if (res.code === 200) {
                        for (let i = 0, len = res.data.length; i < len; i++) {
                            res.data[i].huanjieNum = (res.data[i].nodeList && res.data[i].nodeList.length) || 0;
                            res.data[i].createTime = layui.util.toDateString(res.data[i].createTime, 'yyyy-MM-dd HH:mm:ss')
                        }
                        resolve(res.data);
                    }
                },
                error(err) {
                    reject(err)
                }
            })
        })
    }

    // // 更新模板列表
    function updateTamplateTable() {
        getTemplateList().then(res => {
            ncpData = res;
            tableNcp.reload({
                id: 'idTemplateTable',
                data: ncpData
            });
        }).catch(err => console.log(err));
    }

    let ncpData = [];

    let tableNcp;
    var layer;
    layui.use(['table', 'laypage', 'layer'], async function () {
        var table = layui.table,
            laypage = layui.laypage;
        layer = layui.layer;

        await getTemplateList().then(res => {
            ncpData = res
        }).catch(err => console.log(err));
        //渲染表格
        tableNcp = table.render({
            elem: '#list',
            id: 'idTemplateTable',
            data: ncpData,
            skin: 'line',
            page: true,
            // toolbar: 'default',
            cols: [[
                {field: 'tpName', title: '模板名称', sort: true},
                {field: 'createTime', title: '创建时间'},
                {field: 'qyid', title: '创建人'},
           /*     {field: 'huanjieNum', title: '环节数量'},*/
                {title: '操作', fixed: 'right', width: 150, align: 'left', toolbar: '#toolbarDemo'}
            ]]
        });
        // 监听表格行的详情、编辑删除时间
        table.on('tool(templateList)', function (obj) {
            var data = obj.data;
            let layEvent = obj.event;
            if (layEvent === 'detail') { //查看
                showTemplate('.view-template-container');
                getTemplateDetail(data.id).then(res => {
                    renderHuanjieDataView(res)
                }).catch(err => console.log(err));
            } else if (layEvent === 'delete') { //删除
                layer.confirm('真的删除行么', function (index) {
                    deleteTemplate(data.id).then(res => {
                        layer.msg(res.message);
                        obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                        layer.close(index);
                        updateTamplateTable(); // 更新列表
                    }).catch(err => {
                        layer.close(index);
                        layer.error(err.message)
                    })
                    //向服务端发送删除指令
                });
            }
            // else if(layEvent === 'update'){ //编辑
            // 	showTemplate('.edit-template-container');
            //   renderHuanjieDataEdit(huanjieListData)
            // 	//同步更新缓存对应的值
            // 	// obj.update({
            // 	// 	username: '123'
            // 	// 	,title: 'xxx'
            // 	// });
            // } else if(layEvent === 'LAYTABLE_TIPS'){
            // 	layer.alert('Hi，头部工具栏扩展的右侧图标。');
            // }
        })
    });

    // 获取模板详情
    function getTemplateDetail(tId) {
        return new Promise((resolve, reject) => {
            $.ajax({
                url: BASE_URL + '/queryTpByid/' + tId,
                type: 'get',
                contentType: 'application/json;charset=utf-8;',
                success: function (res) {
                    if (res.code === 200) {
                        resolve(res.data);
                    }
                },
                error(err) {
                    reject(err)
                }
            })
        })
    }

    // 删除模板
    function deleteTemplate(tId) {
        return new Promise((resolve, reject) => {
            $.ajax({
                url: BASE_URL + '/deleteTpById/' + tId,
                type: 'post',
                contentType: 'application/json;charset=utf-8;',
                success: function (res) {
                    if (res.code === 200) {
                        resolve(res);
                    }
                },
                error(err) {
                    reject(err)
                }
            })
        })
    }


</script>
</body>
</html>
